package com.telit.dispose.service.dispose.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.telit.dispose.dao.dispose.PlatMetaFieldMapper;
import com.telit.dispose.dao.dispose.PlatMetaTableMapper;
import com.telit.dispose.entity.dispose.PlatMetaFieldEntity;
import com.telit.dispose.entity.dispose.PlatMetaTableEntity;
import com.telit.dispose.service.dispose.PlatMetaFieldService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;


/**
 * 元数据-字段业务逻辑实现
 * Create by Chencf 2022/08/05
 */

@Service
public class PlatMetaFieldServiceImpl implements PlatMetaFieldService {

    private static final String[] PRIMARY_FIELD_CODE = new String[]{
            "id", "code", "name", "delete_flag", "create_by", "create_name",
            "create_date", "update_by", "update_name", "update_date",
            "tentment_id"
    };

    @Autowired
    private PlatMetaFieldMapper platMetaFieldMapper;

    @Autowired
    private PlatMetaTableMapper platMetaTableMapper;

    /**
     * 获取默认的查询条件
     * @param params    参数集
     * @return PlusQueryWrapper
     */
//    private PlusQueryWrapper getDefaultQueryWrapper(Map<String, Object> params) {
//        PlusQueryWrapper queryWrapper = new PlusQueryWrapper<>();
//        queryWrapper.setEntityClass(PlatMetaFieldEntity.class).setParams(params);
//        queryWrapper.fLikes("description");
//        queryWrapper.fEqs("id","code","type","sort","deleteFlag","createBy","updateBy");
//        return queryWrapper;
//    }

    /**
     * 检查是否为关键字段
     *
     * @param code 字段编码
     *
     * @return Boolean
     */
    private boolean isPrimaryFieldCode(String code) {
        for (int i = 0; i < PRIMARY_FIELD_CODE.length; i++) {
            if (PRIMARY_FIELD_CODE[i].equals(code)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public boolean addPlatMetaField(PlatMetaFieldEntity entity) {
        //  validateInsertException(entity);

        /*if (isPrimaryFieldCode(entity.getCode())) {
            throw new RuntimeException("指定的编码为关键字：" + entity.getCode());
        }*/

        QueryWrapper<PlatMetaFieldEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("code", entity.getCode());
        wrapper.eq("table_id", entity.getTableId());
        wrapper.eq("delete_flag", "0");
        int count = platMetaFieldMapper.selectCount(wrapper);
        if (count > 0) {
            throw new RuntimeException("指定的编码已存在：" + entity.getCode());
        }
        //wrapperInsertEntity(entity);
        return platMetaFieldMapper.insert(entity) > 0;
    }

    @Override
    public boolean createPlatMetaField(String id) {
        boolean flag = false;
        if (StringUtils.isNotBlank(id)) {
            PlatMetaFieldEntity entity = platMetaFieldMapper.selectById(id);
            if (entity != null) {
                //1.先获取表编码
                PlatMetaTableEntity table = platMetaTableMapper.selectById(entity.getTableId());
                entity.setTableCode(table.getPrefix() + table.getCode());
                List<PlatMetaFieldEntity> items = platMetaFieldMapper.selectFieldByTableAndField(
                        entity.getTableCode(),
                        entity.getCode()
                );
                //1.先创建物理字段
                if (items == null || items.size() == 0) {
                    platMetaFieldMapper.createField(entity);
                }
                //2.修改字段的创建状态
                entity.setIsCreate(PlatMetaTableEntity.IS_CREATED_YES);
                //   wrapperUpdateEntity(entity);
                platMetaFieldMapper.updateById(entity);
                flag = true;
            }
        }
        return flag;
    }

    @Override
    public boolean updatePlatMetaFieldById(PlatMetaFieldEntity entity) {
        //validateNotNullException(entity);
        if (StringUtils.isNotBlank(entity.getId())) {
            PlatMetaFieldEntity item = platMetaFieldMapper.selectById(entity.getId());
            if (item != null) {
                //不允许修改字段的code和is_create
                entity.setCode(item.getCode());
                entity.setIsCreate(item.getIsCreate());
                //  wrapperUpdateEntity(entity);
                return platMetaFieldMapper.updateById(entity) > 0;
            }
        }
        return false;
    }

    @Override
    public boolean deletePlatMetaFieldById(String id) {
        if (StringUtils.isNotBlank(id)) {
            PlatMetaFieldEntity entity = platMetaFieldMapper.selectById(id);
            if (entity != null) {
                // entity.setDeleteFlag(ConstUtil.DELETE_FLAG_DISABLED);
                // wrapperUpdateEntity(entity);
                return platMetaFieldMapper.updateById(entity) > 0;
            }
        }
        return false;
    }

    @Override
    public PlatMetaFieldEntity getPlatMetaFieldById(String id) {
        PlatMetaFieldEntity entity = null;
        if (StringUtils.isNotBlank(id)) {
            entity = platMetaFieldMapper.selectById(id);
        }
        return entity;
    }

    @Override
    public List<PlatMetaFieldEntity> getPlatMetaFieldListByTableId(String tableId) {
        List<PlatMetaFieldEntity> items = null;
        if (StringUtils.isNotBlank(tableId)) {
            QueryWrapper<PlatMetaFieldEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("table_id", tableId);
            items = platMetaFieldMapper.selectList(wrapper);
        }
        if (items == null) {
            items = new ArrayList<>();
        }
        return items;
    }

    @Override
    public boolean deletePlatMetaFieldByTableId(String tableId) {
        if (StringUtils.isNotBlank(tableId)) {
            return platMetaFieldMapper.deletePlatMetaFieldByTableId(tableId) > 0;
        }
        return false;
    }

    @Override
    public boolean checkPlatMetaFieldExists(PlatMetaFieldEntity field, String tableId) {
        if (field != null && StringUtils.isNotBlank(tableId)) {
            QueryWrapper<PlatMetaFieldEntity> wrapper = new QueryWrapper<>();
            if (StringUtils.isNotBlank(field.getId())) {
                wrapper.eq("id", field.getId());
            }
            if (StringUtils.isNotBlank(field.getCode())) {
                wrapper.eq("code", field.getCode());
            }
            wrapper.eq("table_id", tableId);
            return platMetaFieldMapper.selectCount(wrapper) > 0;
        }
        return false;
    }

}
